﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace TA.DotNetUtils
{
	public static class _ObjectExtensions
	{
		public static object Eval(this object oThis, string propertyPath)
		{
			string propName = propertyPath;

			int dotPos = propertyPath.IndexOf(".");
			if (dotPos != -1)
				propName = propertyPath.Substring(0, dotPos);

			object value = null;
			if (oThis is IPropertiesContainer)
			{
				value = ((IPropertiesContainer)oThis).GetValue(propName);
			}
			else
			{
				PropertyInfo pinfo = oThis.GetType().GetProperty(propName);
				if (pinfo == null)
					throw new ArgumentException("Property '" + propName + "' not found.");
				value = pinfo.GetValue(oThis, new object[0]);
			}
			if (dotPos == -1 || value == null) return value;

			return value.Eval(propertyPath.Substring(dotPos + 1));
		}
		public static void Store(this object This, string propertyPath, object value)
		{
			object container = This;
			int dotPos = propertyPath.LastIndexOf(".");
			string propName = propertyPath;

			if (dotPos != -1)
			{
				propName = propertyPath.Substring(dotPos + 1);
				string pathOnly = propertyPath.Substring(0, dotPos);
				container = This.Eval(pathOnly);
			}

			if (container is IPropertiesContainer)
			{
				((IPropertiesContainer)container).SetValue(propName, value);
			}
			else
			{
				PropertyInfo pinfo = container.GetType().GetProperty(propName);
				if (pinfo == null)
					throw new ArgumentException("Property '" + propName + "' not found.");
				pinfo.SetValue(container, value, new object[0]);
			}
		}
	}
}